<?php
namespace app\admin\controller;


use think\facade\Config;
use app\BaseController;
use think\facade\Db;
use think\facade\Session;
use think\facade\Validate;
use think\exception\ValidateException;

/**
 * 后台登录
 * Class Login
 * @package app\admin\controller
 */
class Login extends BaseController
{
    public function captcha($id = '')
    {
        return captcha($id);
    }
     /* 后台登录
     * @return mixed
     */
    public function index()
    {


        return $this->fetch("index");
    }

    /**
     * 登录验证
     * @return string
     */
    public function submit()
    {
        if ($this->request->isPost()) {
            $data            = $this->request->only(['username', 'password', 'captcha']);

            try {

                validate(\app\admin\validate\Login::class)->check($data);
            } catch (ValidateException $e) {
                // 验证失败 输出错误信息
                $this->error($e->getError());
            }

            $where['username'] = $data['username'];

            $where['password'] = md5($data['password'] . Config::get('app.salt'));

            $admin_user = Db::name('admin_user')->field('id,username,status')->where($where)->find();

            if (!empty($admin_user)) {
                if ($admin_user['status'] != 1) {
                    $this->error('当前用户已禁用');
                } else {
                    Session::set('admin_id', $admin_user['id']);
                    Session::set('admin_name', $admin_user['username']);
                    Db::name('admin_user')->update(
                        [
                            'last_login_time' => date('Y-m-d H:i:s', time()),
                            'last_login_ip'   => $this->request->ip(),
                            'id'              => $admin_user['id']
                        ]
                    );
                    $this->success('登录成功', 'admin/Index/index');
                }
            } else {
                $this->error('用户名或密码错误');
            }

        }
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        Session::delete('admin_id');
        Session::delete('admin_name');
        $this->success('退出成功', 'admin/login/index');
    }
}
